package tom.webflux.service;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.server.ServerRequest;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import tom.webflux.model.User;

import java.util.Map;
import java.util.Optional;
import java.util.function.Function;

/**
 * web-flux应用返回的是Mono和Flux
 * @author ZHUFEIFEI
 */
@Slf4j
@Service
public class UserService {

    private Map<Long, User> memStore ;

    public UserService() {
        this.memStore = Maps.newHashMap();
        this.memStore.put(1L, new User(1L, "tom"));
        this.memStore.put(2L, new User(2L, "cat"));
        this.memStore.put(3L, new User(3L, "dog"));
    }

    /**
     * @param request
     * @return
     */
    public Mono<User> findById(ServerRequest request) {
        return Mono.just(Long.parseUnsignedLong(Optional.of(request.pathVariable("id"))
                .orElseThrow(() -> new IllegalArgumentException("path id can not be null"))))
                .flatMap((id) -> Mono.just(this.memStore.get(id)));
    }

    public Flux<User> findAll() {
        return Flux.fromIterable(this.memStore.values());
    }

    public Mono<Void> create(ServerRequest request) {
        Mono<User> user = request.bodyToMono(User.class);
        //log()打印
        return user.doOnNext((u) -> {
            log.info("add user : {}", u);
            memStore.put(u.getId(), u);
        }).log().then();
    }

    public Mono<Void> delete(ServerRequest request) {
        return Mono.just(Long.parseUnsignedLong(Optional.of(request.pathVariable("id"))
                .orElseThrow(() -> new IllegalArgumentException("path id can not be null"))))
                .doOnNext((id) -> {
                    log.info("remove user : {}", id);
                   this.memStore.remove(id);
                })
                //打印
                .log()
                //then 返回Mono<Void>，只发送代表完成的信息，不包含任何内容
                .then();
    }

}
